package com.billing.web.controller.compensation;

import java.io.UnsupportedEncodingException;
import java.lang.reflect.InvocationTargetException;
import java.net.URLDecoder;
import java.security.acl.Owner;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.billing.model.entity.TPerformance;
import com.billing.model.entity.PerformanceList;
import com.billing.model.entity.TAnnualBonus;
import com.billing.model.entity.TDept;
import com.billing.model.entity.TLatedeductions;
import com.billing.model.entity.TSubsidy;
import com.billing.model.entity.TUser;
import com.billing.model.entity.TUserList;
import com.billing.model.entity.TUserPay;
import com.billing.service.AnnualBonusService;
import com.billing.service.DeptService;
import com.billing.service.LatedeductionsService;
import com.billing.service.PerformanceService;
import com.billing.service.SalaryCalculationService;
import com.billing.service.SubsidyService;
import com.billing.service.UserPayService;
import com.billing.service.UserService;
import com.billing.utils.MD5Util;
import com.billing.web.controller.archives.ImportExcelUntil;
import com.fasterxml.jackson.annotation.JsonTypeInfo.Id;
import com.mchange.v3.hocon.HoconUtils;

/**
 * 薪酬设置
 * @author Administrator
 *
 */
@RequestMapping(value="/salaryc")
@Controller
public class SalaryCalculationController {

	@Resource
	private SalaryCalculationService salaryCalculationService;
	@Resource
	private LatedeductionsService latedeductionsService;
	@Resource
	private UserService userService;
	@Resource
	private DeptService deptService;
	@Resource
	private UserPayService userPayService; 
	@Resource
	private SubsidyService subsidyService; 
	@Resource
	private AnnualBonusService annualBonusService; 
	@Resource
	private PerformanceService performanceService;
	
	/**
	 * 获取排班列表信息
	 * @param request
	 * @param model
	 * @return
	 * @throws InvocationTargetException 
	 * @throws IllegalAccessException 
	 */
	@RequestMapping(value="/index",method=RequestMethod.GET)
	public String index(HttpServletRequest request, Model model) throws IllegalAccessException, InvocationTargetException{
		int frequency=0;
		int maximumid=0;
		int time = 0;
//		List<TSalaryCalculationRules> scrlist=salaryCalculationService.getSalaryCalculationList(0);
//		TSalaryCalculationRules scr1=new TSalaryCalculationRules();
//		TSalaryCalculationRules scr2=new TSalaryCalculationRules();
//		TSalaryCalculationRules scr3=new TSalaryCalculationRules();
//		TSalaryCalculationRules scr4=new TSalaryCalculationRules();
//		for (TSalaryCalculationRules scr : scrlist) {
//			if(scr.getType()==1){
//				BeanUtils.copyProperties(scr1, scr);
//			}
//			if(scr.getType()==2){
//				BeanUtils.copyProperties(scr2, scr);
//			}
//			if(scr.getType()==3){
//				BeanUtils.copyProperties(scr3, scr);
//			}
//			if(scr.getType()==4){
//				BeanUtils.copyProperties(scr4, scr);
//			}
//		}
		int organizationid=(int) request.getSession().getAttribute("organizationid");
		
		List<TLatedeductions> latelist=latedeductionsService.getTLatedeductionsList(organizationid);
		if(latelist!=null&&latelist.size()>0){
			frequency=latelist.get(0).getFrequency();
		}
		List<TLatedeductions> retreatlist=latedeductionsService.getTLEarlyretreatList(organizationid);
		if(retreatlist!=null&&retreatlist.size()>0){
			time=retreatlist.get(0).getFrequency();
		}
		maximumid=latedeductionsService.getTLatedeductionsMaximumId();
		
//		request.setAttribute("scr1", scr1);
//		request.setAttribute("scr2", scr2);
//		request.setAttribute("scr3", scr3);
//		request.setAttribute("scr4", scr4);
		request.setAttribute("frequency", frequency);
		request.setAttribute("latelist", latelist);
		
		request.setAttribute("retreatlist", retreatlist);
		request.setAttribute("time", time);
		
		request.setAttribute("maximumid", maximumid);
		return "compensation/index";
	}
	
	
	/**
	 * 修改迟到打卡信息--次数
	 * @param request
	 * @param model
	 * @return
	 * @throws InvocationTargetException 
	 * @throws IllegalAccessException 
	 */
	@RequestMapping(value="/insert",method=RequestMethod.POST)
	public String insert(HttpServletRequest request, Model model) throws IllegalAccessException, InvocationTargetException{
		String type = request.getParameter("type");//1：迟到；2：早退
		String tiems = request.getParameter("tiems");//迟到
		String frequency = request.getParameter("frequency");	
		String frequencyEarly = request.getParameter("frequencyEarly");	
		String tiemss = request.getParameter("tiemss");//早退
		int organizationid=(int) request.getSession().getAttribute("organizationid");
		  
		if("1".equals(type)){
			List<TLatedeductions> list=new ArrayList<TLatedeductions>();
			TLatedeductions sp=null;
			if(tiems.lastIndexOf(";")>0){
				String[] tiem=tiems.split(";");
				for (int i = 0; i < tiem.length; i++) {
					sp=new TLatedeductions();
					if(tiem[i].lastIndexOf(",")>0){
						String[] ductions=tiem[i].split(",");
						sp.setStarminutes(Integer.valueOf(ductions[0]));
						sp.setEndminutes(Integer.valueOf(ductions[1]));
						sp.setMoney(Double.valueOf(ductions[2]));
						sp.setFrequency(Integer.valueOf(frequency));
						sp.setOrganizationId(organizationid);
						sp.setType(1); // 类型 1：迟到 2：早退
						sp.setCalculationtype(1); // 计算类型 1：次数方式；2：分钟方式
						list.add(sp);
					}
				}
			}if(list.size()>0){
				latedeductionsService.deleteTLatedeductionss(1,1);//说明：deleteTLatedeductionss(int type,int calculationtype);
				latedeductionsService.insertTLatedeductionsList(list);
			}
		}else if("2".equals(type)){
			
			List<TLatedeductions> list=new ArrayList<TLatedeductions>();
			TLatedeductions sp=null;
			if(tiemss.lastIndexOf(";")>0){
				String[] tiem=tiemss.split(";");
				for (int i = 0; i < tiem.length; i++) {
					sp=new TLatedeductions();
					if(tiem[i].lastIndexOf(",")>0){
						String[] ductions=tiem[i].split(",");
						sp.setStarminutes(Integer.valueOf(ductions[0]));
						sp.setEndminutes(Integer.valueOf(ductions[1]));
						sp.setMoney(Double.valueOf(ductions[2]));
						sp.setFrequency(Integer.valueOf(frequencyEarly));
						sp.setOrganizationId(organizationid);
						sp.setType(2); // 类型 1：迟到 2：早退
						sp.setCalculationtype(2); // 计算类型 1：次数方式；2：分钟方式
						list.add(sp);
					}
				}
			}if(list.size()>0){
				latedeductionsService.deleteEarlyretreat(2,2);//说明：deleteTLatedeductionss(int type,int calculationtype);
				latedeductionsService.insertTLatedeductionsList(list);
			}
			
		}
		
		request.setAttribute("msg", "保存成功!");
		return index(request, model);
	}
	
	
	
	/**
	 * 获取用户信息
	 * @param request
	 * @param model
	 * @return
	 */
	@RequestMapping(value="/userindex",method=RequestMethod.GET)
	public String userindex(HttpServletRequest request, Model model){
		String name = request.getParameter("name");
		String dept = request.getParameter("dept");
		String jobnumber = request.getParameter("jobnumber");
		int pageSize = 10;
		try {
			if (dept!=null&&dept.length() > 0) {
				dept = URLDecoder.decode(URLDecoder.decode(dept, "UTF-8"),"UTF-8");
			}
			if (name!=null&&name.length() > 0) {
				name = URLDecoder.decode(URLDecoder.decode(name, "UTF-8"),"UTF-8");
			}
		} catch (UnsupportedEncodingException e) {
		}
		List<TDept> deptlist=deptService.getTDeptlist();
		request.setAttribute("name", name);
		request.setAttribute("dept", dept);
		request.setAttribute("jobnumber", jobnumber);
		request.setAttribute("deptlist", deptlist);
		Long starttime = 0l;
		Long endtime = 0l;
		// 获取当前页数
		int currentPage = 1;
		try {
			currentPage = new Integer(request.getParameter("currentPage"));
		} catch (Exception e) {
		}
		currentPage = currentPage <= 0 ? 1 : currentPage;
		int organizationid=(int) request.getSession().getAttribute("organizationid");
		int totalNum = userService.selectTUserNum(name, dept, starttime, endtime, jobnumber,organizationid);
		int totalPage = totalNum / pageSize;
		if (totalNum % pageSize != 0) {
			totalPage++;	
		}
		totalPage = totalPage <= 0 ? 1 : totalPage;
		currentPage = currentPage > totalPage ? totalPage : currentPage;
		List<TUser> list=userService.selectTUserList(name, dept, starttime, endtime,jobnumber,organizationid, (currentPage - 1) * pageSize, pageSize);
		request.setAttribute("totalNum", totalNum);
		request.setAttribute("list", list);
		request.setAttribute("currentPage", currentPage);
        request.setAttribute("totalNum", totalNum);
        request.setAttribute("totalPage", totalPage);
		return "compensation/userindex";
	}
	
	
	/**
	 * 薪酬设置
	 * @param request
	 * @param model
	 * @return
	 */
	@RequestMapping(value="/insertUser",method=RequestMethod.GET)
	public String insertUser(HttpServletRequest request, Model model){
		String id=request.getParameter("id");
		TUser user=userService.selectTUserPayId(id);
		TUserPay pay=new TUserPay();
		int i=0;
		if(user!=null){
			if(user.getPaylist()!=null&&user.getPaylist().size()>0){
				pay=user.getPaylist().get(0);
				i=user.getPaylist().size();
			}
		}
		request.setAttribute("user", user);
		request.setAttribute("pay", pay);
		request.setAttribute("i", i);
		return "compensation/insertuser";
	}
	
	/**
	 * 薪酬设置
	 * @param request
	 * @param model
	 * @return
	 */
	@RequestMapping(value="/insertUserPay",method=RequestMethod.POST)
	public String insertUserPay(HttpServletRequest request, Model model){
		String userid=request.getParameter("userid");
		String basesalary=request.getParameter("basesalary");
		String status=request.getParameter("status");
		String days=request.getParameter("days");
		String pays=request.getParameter("pays");
		String basicsalary=request.getParameter("basicsalary");
		String basicstatus=request.getParameter("basicstatus");
		String cardinalnumber=request.getParameter("cardinalnumber");
		String radix=request.getParameter("radix");
		TUser user=userService.selectTUserPayId(userid);
		
		if(user!=null){
			List<TUserPay> userpaylist=new ArrayList<TUserPay>();
			TUserPay userpay=new TUserPay(); 
			if(pays.lastIndexOf(";")>0){
				String[] pay=pays.split(";");
				for (int i = 0; i < pay.length; i++) {
					if(pay[i].lastIndexOf(",")>0){
						String[] salary=pay[i].split(",");
						if(salary.length >= 2){
							userpay=new TUserPay();
							userpay.setUserId(user.getId());
							userpay.setStatus(Integer.valueOf(status));
							userpay.setBasesalary(Double.valueOf(basesalary));
							userpay.setDays(Integer.valueOf(days));
							userpay.setCardinalNumber(Double.valueOf(cardinalnumber));
							userpay.setRadix(Integer.valueOf(radix));
							userpay.setBasicSalary(Double.valueOf(basicsalary));
							userpay.setBasicStatus(Integer.valueOf(basicstatus));
							Pattern pattern = Pattern.compile("^(-?//d+)(//.//d+)?$");
							if (Double.parseDouble(salary[1]) < 1) {
								userpay.setAchievement(Double.parseDouble(salary[0].toString()));
								userpay.setProportions(Double.parseDouble(salary[1].toString()));
								TUserPay userP = userPayService.selectTUserPayUserid(userid);
								userpay.setSalary(userP.getSalary());
								userpay.setType(userP.getType());
							}else{
								userpay.setSalary(Double.valueOf(salary[0].toString()));
								userpay.setType(Integer.valueOf(salary[1].toString()));
							}
						}
						if (salary.length >= 4) {
							userpay.setAchievement(Double.parseDouble(salary[2].toString()));
							userpay.setProportions(Double.parseDouble(salary[3].toString()));
						}
						userpaylist.add(userpay);
					}
				}
			}
			if(userpaylist.size()>0){
				userPayService.deleteTUserPay(user.getId());
				userPayService.insertTUserPayList(userpaylist);
			}
			user.setPaylist(userpaylist);
			request.setAttribute("msg", "薪酬设置成功!");
		}
		TUserPay pay=new TUserPay();
		int i=0;
		if(user!=null){
			if(user.getPaylist()!=null&&user.getPaylist().size()>0){
				pay=user.getPaylist().get(0);
				i=user.getPaylist().size();
			}
		}
		request.setAttribute("user", user);
		request.setAttribute("pay", pay);
		request.setAttribute("i", i);
		return "compensation/insertuser";
	}
	
	
	/**
	 * 补贴设置
	 * @param request
	 * @param model
	 * @return
	 */
	@RequestMapping(value="/getSubsidy",method=RequestMethod.GET)
	public String getSubsidy(HttpServletRequest request, Model model){
		String id=request.getParameter("id");
		TUser user=userService.getTSubsidyById(id);
		int i=0;
		if(user!=null){
			if(user.getSublist()!=null){
				i=user.getSublist().size();
			}
		}
		request.setAttribute("user", user);
		request.setAttribute("i", i);
		return "compensation/insertsubsidy";
	}
	
	/**
	 * 补贴设置
	 * @param request
	 * @param model
	 * @return
	 */
	@RequestMapping(value="/insertSubsidy",method=RequestMethod.POST)
	public String insertSubsidy(HttpServletRequest request, Model model){
		String userid=request.getParameter("userid");
		String pays=request.getParameter("pays");
		TUser user=userService.getTSubsidyById(userid);
		if(user!=null){
			List<TSubsidy> sublist=new ArrayList<TSubsidy>();
			TSubsidy sub=new TSubsidy(); 
			if(pays.lastIndexOf(";")>0){
				String[] pay=pays.split(";");
				for (int i = 0; i < pay.length; i++) {
					if(pay[i].lastIndexOf(",")>0){
						String[] salary=pay[i].split(",");
						if(salary.length >= 2){
							sub=new TSubsidy();
							sub.setUserId(user.getId());
							sub.setName(salary[0].toString());
							sub.setMoney(Double.valueOf(salary[1].toString()));
							sublist.add(sub);
						}
					}
				}
			}
			subsidyService.deleteTSubsidyByid(user.getId());
			if(sublist.size()>0){
				subsidyService.insertTSubsidyList(sublist);
			}
			user.setSublist(sublist);
			request.setAttribute("msg", "补贴设置成功!");
		}
		int i=0;
		if(user!=null){
			if(user.getSublist()!=null){
				i=user.getSublist().size();
			}
		}
		request.setAttribute("user", user);
		request.setAttribute("i", i);
		return "compensation/insertsubsidy";
	}
	
	
	/**
	 * 获取年终奖列表
	 * @param request
	 * @param model
	 * @return
	 */
	@RequestMapping(value="/selectAnnualbonus",method=RequestMethod.GET)
	public String selectAnnualbonus(HttpServletRequest request, Model model){
		String userid=request.getParameter("id");
		String year=request.getParameter("year");
		int pageSize = 10;
		// 获取当前页数
		int currentPage = 1;
		try {
			currentPage = new Integer(request.getParameter("currentPage"));
		} catch (Exception e) {
		}
		currentPage = currentPage <= 0 ? 1 : currentPage;
		int totalNum = annualBonusService.selectTAnnualBonusNum(userid, year);
		int totalPage = totalNum / pageSize;
		if (totalNum % pageSize != 0) {
			totalPage++;	
		}
		totalPage = totalPage <= 0 ? 1 : totalPage;
		currentPage = currentPage > totalPage ? totalPage : currentPage;
		List<TAnnualBonus> list=annualBonusService.getTAnnualBonusList(userid, year, (currentPage - 1) * pageSize, pageSize);
		request.setAttribute("list", list);
		request.setAttribute("currentPage", currentPage);
        request.setAttribute("totalNum", totalNum);
        request.setAttribute("totalPage", totalPage);
        request.setAttribute("id", userid);
        request.setAttribute("year", year);
		return "compensation/annualbonusindex";
	}
	
	/**
	 * 年终奖设置
	 * @param request
	 * @param model
	 * @return
	 */
	@RequestMapping(value="/getAnnualbonus",method=RequestMethod.GET)
	public String getAnnualbonus(HttpServletRequest request, Model model){
		String id=request.getParameter("id");
		TUser user=userService.selectTUserId(id);
		request.setAttribute("user", user);
		return "compensation/insertannualbonus";
	}
	
	
	/**
	 * 年终奖设置
	 * @param request
	 * @param model
	 * @return
	 */
	@RequestMapping(value="/insertAnnualbonus",method=RequestMethod.POST)
	public String insertAnnualbonus(HttpServletRequest request, Model model){
		String userid=request.getParameter("userid");
		String year=request.getParameter("year");
		String taxabletime=request.getParameter("taxabletime");
		String money=request.getParameter("money");
		TUser user=userService.selectTUserId(userid);
		TAnnualBonus bonus=new TAnnualBonus();
		bonus.setUserId(user.getId());
		bonus.setMoney(Double.valueOf(money));
		bonus.setYear(Integer.valueOf(year));
		bonus.setTaxableTime(taxabletime);
		annualBonusService.insertTAnnualBonus(bonus);
		request.setAttribute("msg", "年终奖设置成功!");
		request.setAttribute("bonus", bonus);
		request.setAttribute("user", user);
		return "compensation/insertannualbonus";
	}
	
	
	/**
	 * 删除年终奖
	 * @param request
	 * @param model
	 * @return
	 */
	@RequestMapping(value="/deleteAnnualbonus",method=RequestMethod.POST)
	public String deleteAnnualbonus(HttpServletRequest request, Model model){
		String id = request.getParameter("id");
		if(id!=null&&id!=""){
			annualBonusService.deleteTAnnualBonusByid(Integer.valueOf(id));
		}
		return selectAnnualbonus(request, model);
	}
	
	@RequestMapping(value="performance",method=RequestMethod.GET)
	public String performance(HttpServletRequest request,Model model){
		String name = request.getParameter("name");
		TUserPay userPay = null;
		int userid = 0;
		if (name != null && name != "") {
			 userPay = userPayService.getPayByUsername(name);
			 userid = userPay.getUserId();
		}
		List<Map<String, Object>> performances = performanceService.getPerformanceList(userid);
		request.setAttribute("performances", performances);
		request.setAttribute("name", name);
		return "compensation/performance";
	}
	@RequestMapping(value="addPerformance", method=RequestMethod.GET)
	public String addPerformance(HttpServletRequest request,Model model){
		
		return "compensation/addPerformance";
	}
	
	@RequestMapping(value="save",method=RequestMethod.POST)
	@ResponseBody
	public String save(HttpServletRequest request){
		String name = request.getParameter("name");
		String workload = request.getParameter("workload");
		TUserPay userPay = userPayService.getPayByUsername(name);
		int type = userPay.getType();
		TPerformance performance = new TPerformance();
		if (type == 1) {
			performance.setHour(Integer.parseInt(workload));
			performance.setAmount(Integer.parseInt(workload)*userPay.getSalary());
		}
		if (type == 2) {
			performance.setPeice(Integer.parseInt(workload));
			performance.setAmount(Integer.parseInt(workload)*userPay.getSalary());
		}
		if (type == 3) {
			performance.setTon(Integer.parseInt(workload));
			performance.setAmount(Integer.parseInt(workload)*userPay.getSalary());
		}
		performance.setUserid(userPay.getUserId());
		int i = performanceService.insert(performance);
		if (i > 0) {
			return "addok";
		}else{
			return "addno";
		}
	}
	
	//导入页面
	@RequestMapping(value="/importpage",method=RequestMethod.GET)
	public String importpage(HttpServletRequest request, Model model){
		return "compensation/importBill";
	}
	@RequestMapping(value = "improtExcel", method = RequestMethod.POST)
    public String improtExcel(HttpServletRequest request, @RequestParam(value="uploadFile") MultipartFile file) {
        int organizationId=(int) request.getSession().getAttribute("organizationid");
        try {
            List<Map<String, Object>> list = ImportExcelUntil.importExcel(file, new PerformanceList());
            
            for(Map m : list){
            	PerformanceList performance = new PerformanceList();
            	String name = m.get("name").toString();
            	String peice = m.get("hour").toString();
            	String ton = m.get("ton").toString();
            	String hour = m.get("hour").toString();
            	String amount = m.get("amount").toString();
            	TUserPay userPay = userPayService.getPayByUsername(name);
            	performance.setUserid(userPay.getUserId());
            	performance.setAmount(Double.parseDouble(amount));
            	if (ton != null && !ton.equals("") && !ton.equals("0.0")) {
            		performance.setTon(Integer.parseInt(ton));
				}
            	if (hour != null && !hour.equals("") && !ton.equals("0.0")) {
					performance.setHour(Integer.parseInt(hour));
				}
            	if (peice != null && !peice.equals("") && !ton.equals("0.0")) {
					performance.setPeice(Integer.parseInt(peice));
				}
            	performanceService.insertPerformanceList(performance);
            	//userService.insertTUserList(tus);
            }
            
            
        } catch (Exception e) {
            e.printStackTrace();
            request.setAttribute("msg", "导入格式有误已中断!");
            return "compensation/importBill";
        }
        request.setAttribute("msg", "导入成功!");
        return "compensation/importBill";
    }
}
